<template>
  <div>
    <van-field
      readonly
      clickable
      label="选择区域"
      :value="label"
      placeholder="请选择区域"
      @click="showAddressPicker = true"
      :rules="[{ required: true, message: '请选择区域' }]"
    />

    <!-- 省市县picker -->
    <van-popup v-model="showAddressPicker" position="bottom" get-container="body">
      <van-area
        ref="area"
        :value="areaVal"
        :area-list="areaList"
        @confirm="onConfirmAddress"
        @cancel="showAddressPicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { required } from "vee-validate/dist/rules";
import zh from "vee-validate/dist/locale/zh_CN";
import { getArea, selectArea } from "@/api/user.js";
import Bus from "./bus";

import areaList from "./area";

export default {
  data() {
    return {
      areaVal: this.value ? `${this.value[2]}` : "",
      areaList,
      showAddressPicker: false,
      label: ''
    };
  },
  props: {
    value: {}
  },
  watch:{
    value(val){
      Bus.$emit("areaChange", val);
      let province, city, county, value;
      if (val) {
        value = val ? `${val[2]}` : undefined;
      } else {
        value = "";
      }

      if (this.areaList.province_list) {
        province = this.areaList.province_list[`${value.substr(0, 2)}0000`];
      }
      if (this.areaList.city_list) {
        city = this.areaList.city_list[`${value.substr(0, 4)}00`];
      }
      if (this.areaList.county_list) {
        county = this.areaList.county_list[value];
      }
      this.label = province && city && county ? `${province}-${city}-${county}` : "";
    }
  },
  computed: {
    // label() {
    //   let province, city, county, value;
    //   if (this.value) {
    //     value = this.value ? `${this.value[2]}` : undefined;
    //   } else {
    //     value = "";
    //   }

    //   if (this.areaList.province_list) {
    //     province = this.areaList.province_list[`${value.substr(0, 2)}0000`];
    //   }
    //   if (this.areaList.city_list) {
    //     city = this.areaList.city_list[`${value.substr(0, 4)}00`];
    //   }
    //   if (this.areaList.county_list) {
    //     county = this.areaList.county_list[value];
    //   }
    //   return province && city && county ? `${province}-${city}-${county}` : "";
    // }
  },
  created() {
    // 获取省市区数据
    // selectArea()
    //   .then(({ data }) => {
    //     this.areaList = {
    //       province_list: data[0],
    //       city_list: data[1],
    //       county_list: data[2]
    //     };
    //   })
    //   .then(res => {
    //     Bus.$emit("areaChange", this.value ? this.value[2] : "");
    //   });
  },
  methods: {
    onConfirmAddress(obj) {
      const code = obj.map(m => m.code);

      this.showAddressPicker = false;

      this.$emit("input", code);
      Bus.$emit("areaChange", code);
    }
  },
  components: {
  }
};
</script>

<style lang='scss'>
</style>
